#!/usr/bin/env bash
set -e
set -u
set -o pipefail


get_current_mutt_config() {
    local dot_mutt_config=${1:?}
    local firstline=
    touch ${dot_mutt_config}
    read -r firstline < ${dot_mutt_config}
    echo ${firstline}
}


mutt_configure_main() {
    local dot_mutt_dir=${1:?}
    local load_current=${2:-"current"}
    local dot_mutt_config=${dot_mutt_dir}/.mutt-config
    local current_mutt_config=$(get_current_mutt_config $dot_mutt_config)

    mkdir -p ${dot_mutt_dir}/tmp

    if [ "current" == "$load_current" ]; then
        echo ${current_mutt_config}/config
    else
        local first=""
        local hit=""
        local done=""
        for file in ${dot_mutt_dir}/var/*; do
            [ -e "$file" ] || continue
            if [ "" == "$first" ]; then
                first="$file"
            fi
            if [ "" == "$current_mutt_config" ]; then
                current_mutt_config="$first"
                echo $first > ${dot_mutt_config}
            fi
            if [ "$hit" == "hit" ]; then
                done="done"
                echo "$file" > ${dot_mutt_config}
                break
            fi
            if [ "$file" == "$current_mutt_config" ]; then
                hit="hit"
            fi
        done

        if [ "$done" != "done" ]; then
            echo "$first" > ${dot_mutt_config}
        fi

        local next_mutt_config=$(get_current_mutt_config $dot_mutt_config)
        echo ${next_mutt_config}/config
    fi
}


mutt_configure_main "${HOME}/.mutt" ${1:-}
